//
//  LeaderAccountingVC.m
//  SelfDrivingTravelling-IOS
//
//  Created by Teplot_01 on 16/8/31.
//  Copyright © 2016年 Teplot_01. All rights reserved.
//

#import "LeaderAccountingVC.h"
#import "LeaderAccountingCell.h"
@interface LeaderAccountingVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@end

@implementation LeaderAccountingVC
{
    UITableView *_tableView;
    NSString *_newString;
//    NSString *_replaceStr;
    
    UITextField *_useTf;
    UITextField *_moneyTf;
    
    //请求下来的字典
    NSDictionary *_responseDic;
    //请求下来的数组
    NSArray *_responseArr;
    
    NSMutableArray *_textFieldArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"记一笔";
    self.view.backgroundColor = White_Color;
    [self initTopView];
    [self requestForSignUpList];
    [self initTableView];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveAction)];
    //去除多余的分割线
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}
- (void)initTopView{
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, KScreenWidth, 60)];
    topView.backgroundColor = superBackgroundColor;
    [self.view addSubview:topView];
    UILabel *useLb = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 40, 35)];
    useLb.text = @"用途";
    useLb.font = [UIFont systemFontOfSize:15];
    [topView addSubview:useLb];
    _useTf = [[UITextField alloc]initWithFrame:CGRectMake(50, 12, 100, 30)];
    _useTf.layer.cornerRadius = 3;
    _useTf.layer.borderWidth = 1;
    _useTf.layer.borderColor = Gray_Color.CGColor;
    _useTf.placeholder = @"请输入消费用途";
    _useTf.font = [UIFont systemFontOfSize:13];
    [topView addSubview:_useTf];
    UILabel *moneyLb = [[UILabel alloc]initWithFrame:CGRectMake(KScreenWidth - 150, 10, 40, 35)];
    moneyLb.text = @"金额";
    moneyLb.font = [UIFont systemFontOfSize:15];
    [topView addSubview:moneyLb];
    _moneyTf = [[UITextField alloc]initWithFrame:CGRectMake(KScreenWidth - 110, 12, 100, 30)];
    _moneyTf.delegate = self;
    _moneyTf.layer.cornerRadius = 3;
    _moneyTf.layer.borderWidth = 1;
    _moneyTf.layer.borderColor = Gray_Color.CGColor;
    _moneyTf.placeholder = @"请输入消费金额";
    _moneyTf.font = [UIFont systemFontOfSize:13];
    [topView addSubview:_moneyTf];
}
- (void)initTableView{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 124, KScreenWidth, KScreenHeight - 64-60)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
}

#pragma - mark UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _responseArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LeaderAccountingCell *cell = [[NSBundle mainBundle]loadNibNamed:@"LeaderAccountingCell" owner:nil options:nil][0];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textField.text = _newString;
    cell.textField.delegate = self;
    cell.textField.tag = indexPath.row;
//    _replaceStr = cell.textField.text;
    cell.name.text = _responseDic[@"list"][indexPath.row][@"name"];
    if ([_responseDic[@"list"][indexPath.row][@"sex"] isEqualToString:@"0"]) {
        cell.sexLb.text = @"女";
    }else{
        cell.sexLb.text = @"男";
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}
#pragma - mrak UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if ([textField isEqual:_moneyTf]) {
        NSString *_content = [textField text];
        int money = [_content doubleValue]/_responseArr.count;
        _newString = [NSString stringWithFormat:@"%d",money];
        [_tableView reloadData];
        _textFieldArr = [[NSMutableArray alloc]init];
        for (int i = 0; i<_responseArr.count; i++){
            [_textFieldArr addObject:_newString];
        }
    }else{
        for (int i = 0; i<_responseArr.count; i++){
            if (textField.tag == i) {
                [_textFieldArr replaceObjectAtIndex:i withObject:textField.text];
            }
        }
    }
}
#pragma - mark 活动报名人员列表
- (void)requestForSignUpList{
    //参数
    
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
    [parameters setValue:@"" forKey:@"userId"];
    [parameters setValue:@"" forKey:@"isMember"];
    [parameters setValue:self.activityId forKey:@"activityID"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/activity/signUpPersonList.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        _responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@>>>>",_responseDic);
        _responseArr = _responseDic[@"list"];
        NSString *error = _responseDic[@"code"];
        if (![_responseDic[@"code"] isEqualToString:@"0000"]&&![_responseDic[@"code"] isEqualToString:@"3003"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
        }
        if ([_responseDic[@"code"] isEqualToString:@"3003"]) {
            [SVProgressHUD showErrorWithStatus:@"暂无报名人员"];
        }
        else{
            //请求成功
//            [SVProgressHUD showSuccessWithStatus:@"列表请求成功"];
            [_tableView reloadData];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请求失败"];
    }];
}
//记一笔
- (NSMutableURLRequest *)postRequestWithURL:(NSString *)url content:(NSString *)text{
    NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request =
    [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded"
   forHTTPHeaderField:@"Contsetent-Type"];
    [request setHTTPBody:data];
    
    return request;
}
- (void)saveAction{
    [_moneyTf endEditing:YES];
    NSMutableArray *contentArr = [[NSMutableArray alloc]init];
    //获取当前时间
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    
    
    //拼接参数字符串
    NSString *strId = [@"activityID=" stringByAppendingString:[NSString stringWithFormat:@"%@",self.activityId]];
    NSString *payTimeStr = [@"&payTime=" stringByAppendingString:dateString];
    NSString *payContentStr = [@"&payContent=" stringByAppendingString:_useTf.text];
    for (int i = 0; i<_responseArr.count; i++){
        NSNumber *strNum = _responseArr[i][@"id"];
        NSString *idStr = strNum.stringValue;
        idStr = [idStr stringByAppendingString:@"-"];
        idStr = [idStr stringByAppendingString:_textFieldArr[i]];
        idStr = [@"&values=" stringByAppendingString:idStr];
        [contentArr addObject:idStr];
    }
    NSString *contentStr = [contentArr componentsJoinedByString:@""];
    contentStr = [NSString stringWithFormat:@"%@%@%@%@",strId, payTimeStr,payContentStr,contentStr];
    
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://115.28.152.130/tour/v1/activity/billing.action"]];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];// 请求
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];// 响应
    NSURLRequest *request = [self postRequestWithURL:@"http://115.28.152.130/tour/v1/activity/billing.action" content:contentStr];
//    NSURLRequest *request = [self postRequestWithURL:@"http://115.28.152.130/tour/v1/activity/billing.action" content:@"activityID=72&payTime=2016.09.22&payContent=大保健&values=31-880&values=36-880&values=37-880"];
    
    NSOperation *operation =
    [manager HTTPRequestOperationWithRequest:request
                                          success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                              // 成功后的处理
                                              NSDictionary *_AccoResponseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                                              NSLog(@"%@>>>>",_AccoResponseDic);
                                              NSString *error = _AccoResponseDic[@"code"];
                                              if (![_AccoResponseDic[@"code"] isEqualToString:@"0000"]) {
                                                  [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
                                              }else{
                                                  //请求成功
                                                  [SVProgressHUD showSuccessWithStatus:@"记账成功"];
                                                  [self.navigationController popViewControllerAnimated:YES];
                                              }
                                              
//                                              NSLog(@"成功了");
                                          }
                                          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                              // 失败后的处理
                                              NSLog(@"失败了");
                                              NSLog(@"%@",error);
                                          }];
    [manager.operationQueue addOperation:operation];
    
    
    //参数
//    NSDictionary *parameters = @{
//                                 @"activityID":[NSString readToNSDefaultsWithKey:kActivityId],
//                                 @"payTime": dateString,
//                                 @"payContent": _useTf.text,
//                                 @"values": @"17-20",
//                                 };
//    
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    
//    [manager POST:@"http://115.28.152.130/tour/v1/activity/billing.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
//        NSDictionary *_AccoResponseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
//        NSLog(@"%@>>>>",_AccoResponseDic);
//        //        NSArray *_responseArr = _responseDic[@"list"];
//        NSString *error = _AccoResponseDic[@"code"];
//        if (![_AccoResponseDic[@"code"] isEqualToString:@"0000"]) {
//            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
//            
//        }else{
//            //请求成功
//            [SVProgressHUD showSuccessWithStatus:@"记账成功"];
////            [self initCollectionView];
//        }
//
//    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
//        [SVProgressHUD showErrorWithStatus:@"记账失败"];
//    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
